﻿// <copyright file="FeedItemCollectionSource.cs" company="Ucaya">
// </copyright>
// <author>Ucaya</author>

namespace Channel9Kinect
{
    #region

    using System;
    using System.ComponentModel.Composition;
    using System.Linq;
    using System.ServiceModel.Syndication;

    using Channel9Kinect.Services;

    #endregion

    public class FeedItemCollectionSource : ViewModelBase, IPagedCollectionSource
    {
        #region Constants and Fields

        private SyndicationFeed feed;

        private Uri feedUri;

        private bool isLoading;

        #endregion

        #region Constructors and Destructors

        public FeedItemCollectionSource()
        {
            ServiceLocator.Instance.SatisfyImportsOnce(this);
        }

        #endregion

        #region Public Events

        public event EventHandler RecreateCollection;

        #endregion

        #region Public Properties

        [Import]
        public FeedService FeedService { get; set; }

        public Uri FeedUri
        {
            get
            {
                return this.feedUri;
            }
            set
            {
                if (this.feedUri != value)
                {
                    this.feedUri = value;
                    this.OnRecreateCollection();
                    this.RaisePropertyChanged(n => n.FeedUri);
                }
            }
        }

        public bool IsLoading
        {
            get
            {
                return this.isLoading;
            }
            set
            {
                if (this.isLoading != value)
                {
                    this.isLoading = value;
                    this.RaisePropertyChanged(n => n.IsLoading);
                }
            }
        }

        #endregion

        #region Methods

        protected virtual void OnRecreateCollection()
        {
            if (this.RecreateCollection != null)
            {
                this.RecreateCollection(this, EventArgs.Empty);
            }
        }

        public async void GetPagedCollection(Action<IPagedCollection> callback, Action<Exception> error, int pageSize)
        {
            if (this.FeedUri == null)
            {
                return;
            }

            this.IsLoading = true;
            this.feed = await this.FeedService.GetFeeds(this.FeedUri);
            var feedPagedCollection = new PagedCollection<SyndicationItem>(this.feed.Items.Count(), asyncLoadPage: req =>
                {
                    req.PostResult(this.feed.Items.Skip(req.Skip).Take(req.PageSize).ToArray());
                }, pageSize: pageSize);

            callback(feedPagedCollection);
            this.IsLoading = false;
        }

        #endregion
    }
}